上一篇解釋 Nuxt 插件 (Plugins)
用於管理特定執行環境的程式碼片段,並在 Nuxt App 自動載入、執行
一貫簡單風格,需要載入的 plugin
列舉於 nuxt.config.js
export default {
plugins: ['~/plugins/my-plugin.js']
}
預設是 SSR + CSR 環境都起作用,若你只需要 Browser 端執行,把 ssr
註記關掉
export default {
plugins: [
/* { src: '~/plugins/my-plugin.js' }, */
{ src: '~/plugins/vue-notifications', ssr: false }
]
}
當不需要 Nuxt context
參數,收納初始化程式碼好用 (像是第三方 Library、Vue Plugins)、注入實例屬性 (Instance Properties)
https://vuejs.org/v2/cookbook/adding-instance-properties.html
像 vue-notifications
初始化,通常每一頁都會用
/pages/product.vue
<template>
<div>
<!-- page component content -->
</div>
</template>
<script>
import Vue from 'vue'
import VueNotifications from 'vue-notifications'
Vue.use(VueNotifications)
export default {
/* page component blah */
}
</script>
重複執行的初始化,直接包成 /plugins/vue-notification-initial.js
/pages/product.vue
import Vue from 'vue'
import VueNotifications from 'vue-notifications'
Vue.use(VueNotifications)
export default {
plugins: [
'~/plugins/my-plugin.js',
'/plugins/vue-notification-initial.js'
]
}
export default ({ app }, inject) => {
/* 直接注入 context.app */
app.myInjectedFunction = (string) => console.log('Okay, another function', string)
/* 透過注入器,注入 context */
inject('myInjectedFunctionB', (string) => console.log('That was easy!', string))
}
export default {
asyncData(context){
context.app.myInjectedFunction('ctx!')
context.app.$myInjectedFunctionB('ctxb!')
}
}
接下來要實作了,把前一篇 Axios 初始化收納進 Plugin
import axios from 'axios'
export default function (ctx, inject) {
axios.defaults.baseURL = 'https://api.example.com'
axios.defaults.headers.common['Authorization'] = 'YUOR_AUTH_TOKEN'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
/* 注入 Nuxt Instance Property */
ctx.$axios = axios
inject('axios', axios)
}
import Axios from 'axios'
export default function (ctx, inject) {
const axios = Axios.create({
baseURL: 'https://api.example.com'
})
axios.defaults.headers.common['Authorization'] = 'YUOR_AUTH_TOKEN'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
/* 注入 Nuxt Instance Property */
ctx.$axios = axios
inject('axios', axios)
}
後來想到,假資料 Nuxt 還不支援,
那假資料宣告是不是可以寫進 Plugins 裡?
import axios from 'axios'
import MockAdapter from 'axios-mock-adapter'
export default function (ctx, inject) {
axios.defaults.baseURL = 'https://api.example.com'
axios.defaults.headers.common['Authorization'] = 'YUOR_AUTH_TOKEN'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
ctx.$axios = axios;
inject('axios', axios)
let mock = new MockAdapter(axios)
mock.onGet('/users').reply(200, {
users: [
{ id: 1, name: 'John Smith' }
]
})
}
完工,這樣全站 測試用 API
& 預設參數
都集中在這隻 Plugin 裡了